<template>
  <div id="CarSharingUser">
    <ul id="ul1">
      <li>
        <el-input v-model="userName" placeholder="请输入"></el-input>
      </li>
      <li>
        <el-button type="primary" @click="queryUserByName">查询</el-button>
        <!-- <el-button type="success" v-power @click="openAddWindow()"
          >添加</el-button
        > -->
      </li>
    </ul>
    <!-- 表格 -->
    <el-table
      :row-style="rowStyle"
      :data="userData"
      border
      style="width: 100%"
      height="500"
    >
      <el-table-column prop="userName" label="用户名"></el-table-column>
      <el-table-column prop="loginName" label="登录名"></el-table-column>
      <el-table-column prop="amount" label="金币">
        <template slot-scope="scope">
          {{ formattedAmount(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column prop="wechatQrCode" label="微信收款码">
            <template slot-scope="scope">
                <el-image 
                    v-if="scope.row.wechatQrCode"
                    :src="`${baseUrl}/image/getImageById/${scope.row.wechatQrCode}`"
                    fit="contain"
                    style="width: 100px; height: auto; cursor: pointer;"
                    @click="handleImagePreview(scope.row.wechatQrCode)">
                </el-image>
            </template>
      </el-table-column>
      <el-table-column prop="alipayQrCode" label="支付宝收款码">
            <template slot-scope="scope">
                <el-image 
                    v-if="scope.row.alipayQrCode"
                    :src="`${baseUrl}/image/getImageById/${scope.row.alipayQrCode}`"
                    fit="contain"
                    style="width: 100px; height: auto; cursor: pointer;"
                    @click="handleImagePreview(scope.row.alipayQrCode)">
                </el-image>
            </template>
      </el-table-column>
        <!-- <el-table-column
        prop="phone"
        label="手机号"
        min-width="200"
      ></el-table-column> -->

      <!-- <el-table-column
        prop="lastLoginTime"
        label="最后登录时间"
        min-width="200"
      ></el-table-column> -->
      <!-- <el-table-column prop="workTime" label=""></el-table-column> -->
      <el-table-column
        prop="createTime"
        label="创建时间"
        min-width="120"
      ></el-table-column>
      <el-table-column
        prop="updateTime"
        label="修改时间"
        min-width="120"
      ></el-table-column>

      <el-table-column fixed="right" label="操作" width="290">
        <template slot-scope="scope" >
          <el-button v-if="scope.row.loginName !='admin'"
          type="primary"
            v-power
            @click="openPay(scope.row, 'updateInfo')"
            size="small"
            >充值</el-button
          >
          <el-button
          type="success"
            v-power
            @click="openUserInfoWindow(scope.row, 'updateInfo')"
            size="small"
            >编辑</el-button
          >
          <el-button 
          v-if="scope.row.loginName !='admin'"
          type="danger"
          v-power
           @click="openDelete(scope.row,'updateInfo')" 
           size="small"
            >注销</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[1, 2, 3, 10]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :background="true"
      style="margin-top: 30px"
    >
    </el-pagination>
    <el-dialog
        v-model="imagePreviewVisible"
        :visible.sync="imagePreviewVisible"
        width="30%"
        :before-close="handleClosePreview">
        <el-image
            style="width: 100%;"
            :src="imagePreviewUrl"
            fit="contain">
        </el-image>
    </el-dialog>
    <el-dialog title="添加员工信息" :visible.sync="userAddWindow" width="30%">
      <el-form
        :model="userForm"
        ref="userForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="userForm.userName"></el-input>
        </el-form-item>
        <el-form-item label="登录名" prop="loginName">
          <el-input v-model="userForm.loginName"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userAddWindow = false">取 消</el-button>
        <el-button @click="resetForm('userForm')">重置</el-button>
        <el-button type="primary" @click="addUserInfo('userForm')"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 详情弹出框 -->
    <el-dialog title="修改用户信息" :visible.sync="userInfoWindow" width="30%">
      <el-form
        :model="userInfo"
        ref="userForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="userInfo.userName"></el-input>
        </el-form-item>
        <el-form-item label="登录名" prop="loginName">
          <el-input v-model="userInfo.loginName"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userInfo.phone"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="phone">
          <el-input v-model="userInfo.newPassword" type="password"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userInfoWindow = false">取 消</el-button>
        <el-button @click="resetForm('userForm')" :disabled="disable"
          >重置</el-button
        >
        <el-button
          @click="updateUserInfo('userForm')"
          :disabled="disable"
          type="primary"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 支付金额 -->
    <el-dialog title="充值金币" :visible.sync="payWindow" width="30%">
      <el-form
        :model="pay"
        ref="userForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="金币" prop="amount">
          <el-input v-model="pay.amount"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button @click="resetForm('userForm')" :disabled="disable"
          >重置</el-button
        >
        <el-button
          @click="updatePay('userForm')"
          :disabled="disable"
          type="primary"
          >确 定</el-button
        >
      </span>
    </el-dialog>
     <!-- 删除 -->
     <el-dialog title="删除用户" :visible.sync="deleteWindow" width="30%">
      <el-form
        :model="userInfo"
        ref="userForm"
        label-width="100px"
        class="demo-ruleForm"
      >
      <div>是否删除用户 {{userInfo.userName}}</div>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteWindow = false">取 消</el-button>
        <el-button @click="resetForm('userForm')" :disabled="disable"
          >重置</el-button
        >
        <el-button 
          @click="deletetUser('userForm')"
          :disabled="disable"
          type="primary"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "CarSharingUser",
  data() {
    return {
      imagePreviewUrl:"",
      imagePreviewVisible:false,
      baseUrl:"http://shuzisan.suguang.cc:8188",
      souquanshow: false,
      souquanid: 0,
      defaultchecked: [],
      disable: true,
      userName: "", // 用户姓名
      userData: [], // 员工查询数据
      userAddWindow: false, // 员工添加窗口控制
      userInfoWindow: false, // 员工信息窗口控制
      payWindow: false, //支付金额窗口控制
      deleteWindow:false,//删除
      selectmenulist: [],
      userForm: {
        // 员工添加对象
        // userName: "", // 员工名称
        // age: "", // 年龄
        // address: 1, // 地址
        // email: "", // 邮箱
      },
      imageUrl: "",
      file: "",
      userInfo: {}, // 员工信息
      pay: {}, //支付金额
      pageSize: 10, // 每页显示的个数
      pageNum: 1, // 起始的页数 表格中当前页面
      total: 0,
      amount: 0,
    };
  },
  computed: {
    formattedAmount() {
      return (row) => {
        const amount = parseFloat(row.amount);
        return isNaN(amount) ? "0.00" : amount.toFixed(2);
      };
    },
  },
  mounted() {
    this.queryUserByName();
  },
  methods: {
    handleClosePreview() {
        this.imagePreviewVisible = false; // 关闭预览弹窗
    },
    handleImagePreview(imgId) {
                this.imagePreviewUrl = this.baseUrl+`/image/getImageById/${imgId}`;
                this.imagePreviewVisible = true; // 打开预览弹窗
            },
    //删除
    openDelete(row, windowType) {
      // 打开删除窗口
      this.userInfo = JSON.parse(JSON.stringify(row));
      this.disable = windowType === "getInfo";
      this.deleteWindow = true;
    },
    //删除
    deletetUser() {
      this.$axios.delete("sysUser/delUserById?id="+this.userInfo.id).then((res) => {
        if (res.status === 200) {
          this.myMessage("success", "恭喜您！成功删除了一条信息！");
          this.deleteWindow = false;
          this.queryUserByName();
        } else {
          this.myMessage("warning", "警告喔！您有一条信息删除失败！");
        }
      });
    },
    openPay(row, windowType) {
      // 打开支付窗口
      this.userInfo = JSON.parse(JSON.stringify(row));
      this.disable = windowType === "getInfo";
      this.payWindow = true;
    },
    updatePay(formName) {
      this.$alert("充值金币为" + this.pay.amount, "充值", {
        confirmButtonText: "确定",
        callback: () => {
          const storedUserInfo = localStorage.getItem("userInfo");
          const parsedUserInfo = JSON.parse(storedUserInfo);
          this.userInfo.loginName = parsedUserInfo.userName;
          this.userInfo.amount = this.pay.amount;
          this.$axios.put("sysUser/amountPay", this.userInfo).then((res) => {
            if (res.status === 200) {
              const amount = this.pay.amount;
              this.$message({
                showClose: true,
                message: `恭喜您！成功充值了 ${amount} 金币！`,
                type: "success",
              });
              this.payWindow = false;
              this.queryUserByName();
            } else {
              this.myMessage("warning", "警告喔！您的充值操作失败！");
            }
          });
        },
      });
    },
    cancel() {
      this.payWindow = false;
      this.pay = {};
    },
    // souquan() {
    //   var menuIds = this.$refs.tree.getCheckedNodes(false, true);
    //   var formdata = new FormData();
    //   formdata.set("userId", this.souquanid);
    //   for (var a in menuIds) {
    //     formdata.append("menuIds", menuIds[a].id);
    //   }
    //   this.$axios.post("sysUser/userPower", formdata).then((res) => {
    //     console.log(res);
    //     this.myMessage("success", "授权成功");
    //     this.souquanshow = false;
    //   });
    // },
    // opsouquanshow(row) {
    //   this.$axios.get("sysUser/getUserPower?userId=" + row.id).then((res) => {
    //     console.log(this.$refs);
    //     const bb = [];
    //     res.data.data.forEach((a) => {
    //       const node = this.$refs.tree.getNode(a).data;
    //       if (node.children.length === 0) {
    //         console.log(node);

    //         bb.push(a);
    //       }
    //     });
    //     this.defaultchecked = bb;
    //     // this.$refs.tree.setCheckedKeys(res.data.data,true)

    //     console.log(res.data);
    //   });
    //   this.souquanid = row.id;
    //   this.souquanshow = true;
    // },
    rowStyle(row) {
      if (row.row.userFlag == 1) {
        return { "background-color": "rgb(233 233 233)" };
      }
    },
    aaaain(a) {
      console.log(a);
      this.userInfo = {};
      this.userInfo.id = a.id;
      this.userInfo.userFlag = a.userFlag;
      this.updateUserInfo();
    },
    beforeAvatarUpload(file) {
      this.file = file;
      this.imageUrl = URL.createObjectURL(file);

      return false;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.queryUserByName();
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.queryUserByName();
      console.log(`当前页: ${val}`);
    },
    updateUserInfo(formName) {
      this.$axios.put("sysUser/updateUser", this.userInfo).then((res) => {
        if (res.status === 200) {
          this.myMessage("success", "恭喜您！成功修改了一条信息！");
          this.userInfoWindow = false;
          this.queryUserByName();
        } else {
          this.myMessage("warning", "警告喔！您有一条信息修改失败！");
        }
      });
    },
    openUserInfoWindow(row, windowType) {
      // 打开修改或详情窗口
      this.userInfo = JSON.parse(JSON.stringify(row));
      this.disable = windowType === "getInfo";
      this.userInfoWindow = true;
    },
    // deleteUserById(id) {
    //   删除信息
    //   this.$confirm("此操作将注销该员工信息, 是否继续?", "提示", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning",
    //   })
    //     .then(() => {
    //       this.userInfo = {};
    //       this.userInfo.id = id;
    //       this.userInfo.isDel = 1;
    //       this.updateUserInfo(userInfo);
    //     })
    //     .catch((error) => {
    //       console.log(error);
    //       this.myMessage("info", "已取消");
    //     });
    // },
    queryUserByName() {
      // 查询员工信息
      this.$axios
        .get("sysUser/getUser", {
          params: {
            userName: this.userName,
            pageNum: this.pageNum,
            pageSize: this.pageSize,
          },
        })
        .then((res) => {
          if (res.status === 200) {
            this.userData = res.data.data.content;
            this.total = res.data.data.totalSize;
          }
        })
        .catch((error) => {
          this.myMessage("error", "错误哦！系统错误，请联系管理员！");
          console.log(error);
        });
    },
    addUserInfo(formName) {
      // 添加
      this.$refs[formName].validate((valid) => {
        if (valid) {
          var formdata = new FormData();
          this.$axios
            .post("sysUser/saveUser", formdata)
            .then((res) => {
              if (res.status === 200) {
                this.myMessage("success", "恭喜您！成功添加了一条信息！");
                this.userAddWindow = false;
                this.$refs[formName].resetFields();
                this.queryUserByName();
              } else {
                this.myMessage("warning", "警告喔！您有一条信息添加失败！");
              }
            })
            .catch((error) => {
              this.myMessage("error", "错误哦！系统错误，请联系管理员！");
              console.log(error);
            });
        } else {
          return false;
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    openAddWindow() {
      this.file = "";
      this.userForm.createUser = JSON.parse(
        window.localStorage.getItem("userInfo")
      ).id;
      this.userForm.updateUser = JSON.parse(
        window.localStorage.getItem("userInfo")
      ).id;
      // 打开添加窗口
      this.userAddWindow = true;
    },
    // 提示信息
    myMessage(type, message) {
      this.$message({
        showClose: true,
        message: message,
        type: type,
      });
    },
    // 表格文字居中

    // 过滤树
    filterNode(value, data) {
      if (!value) return true;
      return data.menuName.indexOf(value) !== -1;
    },
  },
};
</script>

<style lang="scss" scoped>
#ul1 {
  height: 40px;
  margin-bottom: 15px;
  list-style: none;
}
#ul1 li {
  float: left;
  margin-right: 10px;
}
</style>
